package com.njust.diary.service;

import cn.hutool.core.util.StrUtil;
import com.njust.diary.dao.NoteTypeDao;
import com.njust.diary.po.NoteType;
import com.njust.diary.vo.Result;

import java.util.List;

public class NoteTypeService {
    private NoteTypeDao typeDao =new NoteTypeDao();
    public List<NoteType> findTypeList(Integer userId){
        List<NoteType> typeList =typeDao.findTypeListByUserId(userId);
        return  typeList;
    }


    public Result<NoteType> deteleType(String typeId) {
      Result<NoteType> result =new Result<>();
      if(StrUtil.isBlank(typeId)){
          result.setCode(0);
          result.setMsg("请重试");
          return  result;
      }
      long noteCount =typeDao.findNoteCountByTypeId(typeId);
      if(noteCount>0){
          result.setCode(0);
          result.setMsg("该类型存在日记不可删除！");
          return result;

      }
      int row =typeDao.deleteTypeById(typeId);
      if(row>0){
          result.setCode(1);
      }else{
          result.setCode(0);
          result.setMsg("已被删除，删除失败");
      }

      return result;
    }

    public Result<Integer> addOrUpdate(String typeName, Integer userId, String typeId,String uname) {
   Result<Integer> result = new Result<>();
   if(StrUtil.isBlank(typeName)){
       result.setCode(0);
       result.setMsg("类型名称不能为空!");
       return  result;
   }
    Integer code=typeDao.checkTypeName(typeName,userId,typeId);//查此用户的日记类型中有无重复
    if(code ==0){
        result.setCode(0);
        result.setMsg("类型名称已存在，请重新输入!");
        return  result;
    }
    Integer key =null;//
    if(StrUtil.isBlank(typeId)){
      key=typeDao.addType(typeName,userId,uname);//key为主键,即新添加的类型的Id
    }else{
    key=typeDao.updateType(typeName,typeId);//key被影响的日记行数

    }
    if(key>0){
        result.setCode(1);
        result.setResult(key);
    }else{
        result.setCode(0);
        result.setMsg("更新失败");
    }


   return result;
    }
}
